package com.github.data_manage.controller

import com.github.data_manage.common.CommonPage
import com.github.data_manage.common.CommonResult
import com.github.data_manage.config.SystemException
import com.github.data_manage.dao.PersonEducationExperienceDao
import com.github.data_manage.dao.SchoolDao
import com.github.data_manage.domain.po.School
import com.github.data_manage.domain.vo.SchoolMergeVo
import com.github.data_manage.util.PageUtil
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.tags.Tag
import jakarta.persistence.criteria.Predicate
import jakarta.transaction.Transactional
import org.springframework.data.domain.Sort
import org.springframework.data.jpa.domain.Specification
import org.springframework.util.StringUtils
import org.springframework.web.bind.annotation.*

/**
 *@author CHN
 *@since 2024-08-10 10:24
 */
@RestController
@Tag(name = "SchoolController", description = "学校管理")
@RequestMapping("/school")
class SchoolController(
    private val schoolDao: SchoolDao,
    private val personEducationExperienceDao: PersonEducationExperienceDao
) {

    @Operation(description = "学校列表")
    @GetMapping(value = ["/list"])
    fun getCompanyList(@RequestParam(required = false) schoolName: String?): CommonResult<CommonPage<School>> {
        val condition = Specification<School> { root, _, builder ->
            val conditions = mutableListOf<Predicate>()
            if (StringUtils.hasText(schoolName)) {
                conditions.add(
                    builder.like(
                        root.get<String>("schoolName"),
                        "%${schoolName}%"
                    )
                )
            }
            return@Specification builder.and(*conditions.toTypedArray())
        }
        val page = PageUtil.buildJpaPage<School>(1, 9999)
            .withSort(Sort.by("id").descending())

        return CommonResult.success(CommonPage.restPage(schoolDao.findAll(condition, page)))
    }

    @PostMapping("/merge")
    @Operation(description = "学校合并")
    @Transactional(rollbackOn = [Exception::class])
    fun schoolMerge(@RequestBody schoolMergeVo: SchoolMergeVo): CommonResult<Boolean> {
        val dbMainSchool = schoolDao.findSchoolBySchoolNameEquals(schoolMergeVo.mainSchool.schoolName!!)
            ?: throw SystemException("待合并的学校不存在")
        val minorSchoolId = schoolMergeVo.minorSchoolIds.toMutableSet().let {
            it.remove(dbMainSchool.id)
            it.first()
        }
        schoolDao.findById(minorSchoolId).orElseThrow { SystemException("待合并的学校不存在") }
        schoolMergeVo.mainSchool.id = dbMainSchool.id
        schoolDao.save(schoolMergeVo.mainSchool)
        schoolDao.deleteById(minorSchoolId)
        personEducationExperienceDao.mergeSchool(
            schoolMergeVo.mainSchool.id!!,
            schoolMergeVo.mainSchool.schoolName!!,
            minorSchoolId
        )
        return CommonResult.success(true)
    }

}
